<template>
  <div class='dashboard-container'>
    <div class="app-container">
      <el-card shadow="never">
        <el-h3>6组_孟庆特</el-h3>
        <!-- 一、新增试题 -->
        <el-row class="addQuestion">
          <el-button type="success" icon="el-icon-edit" @click="toQuestionNew" :loading="isLoading">新增试题</el-button>
        </el-row>

        <!-- 二、表单筛选区域 -->
        <el-form ref="form" :model="form" label-width="80px" class="ques_form" :disabled="isLoading">
          <div class="filter-container">
            <!-- 第一行 -->
            <el-row :gutter="10">
              <!-- 1.1学科 -->
              <el-col :span="6">
                <el-form-item label="学科">
                  <el-select v-model="form.subjectValue" placeholder="请选择学科"
                    @change="subjectChange(form.subjectValue)">
                    <el-option
                      v-for="subject in form.subjects"
                      :key="subject.value"
                      :label="subject.label"
                      :value="subject.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <!-- 1.2二级目录 -->
              <el-col :span="6">
                <el-form-item label="二级目录">
                  <!-- @change="directoryChange" -->
                  <el-select v-model="form.directoryValue" placeholder="请选择二级目录">
                    <el-option
                      v-for="directory in form.directorys"
                      :key="directory.value"
                      :label="directory.label"
                      :value="directory.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <!-- 1.3标签 -->
              <el-col :span="6">
                <el-form-item label="标签">
                  <el-select v-model="form.tagValue" placeholder="请选择标签">
                    <el-option
                      v-for="tag in form.tags"
                      :key="tag.value"
                      :label="tag.label"
                      :value="tag.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <!-- 1.4关键字 -->
              <el-col :span="6">
                <el-form-item label="关键字">
                  <el-input v-model="form.keyword" placeholder="请输入题干关键字"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第二行 -->
            <el-row :gutter="10">
              <!-- 2.1试题类型 -->
              <el-col :span="6">
                <el-form-item label="试题类型">
                  <el-select v-model="form.questionTypeVal" placeholder="请选择试题类型">
                    <el-option
                      v-for="type in form.questionTypes"
                      :key="type.value"
                      :label="type.label"
                      :value="type.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <!-- 2.2难度 -->
              <el-col :span="6">
                <el-form-item label="难度">
                  <el-select v-model="form.difficultyVal" placeholder="请选择试题难度">
                    <el-option
                      v-for="diff in form.difficultys"
                      :key="diff.value"
                      :label="diff.label"
                      :value="diff.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <!-- 2.3方向 -->
              <el-col :span="6">
                <el-form-item label="方向">
                  <el-select v-model="form.directionVal" placeholder="请选择试题方向">
                    <el-option
                      v-for="direct in form.directions"
                      :key="direct"
                      :label="direct"
                      :value="direct">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <!-- 2.4录入人 -->
              <el-col :span="6">
                <el-form-item label="录入人">
                  <el-select v-model="form.userVal" placeholder="请选择录入人">
                    <el-option
                      v-for="user in form.users"
                      :key="user.id"
                      :label="user.username"
                      :value="user.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第三行 -->
            <el-row :gutter="10">
              <!-- 3.1题目备注 -->
              <el-col :span="6">
                <el-form-item label="题目备注">
                  <el-input v-model="form.remarks" placeholder="请输入题目备注"></el-input>
                </el-form-item>
              </el-col>
              <!-- 3.2企业简称 -->
              <el-col :span="6">
                <el-form-item label="企业简称">
                  <el-input v-model="form.shortName" placeholder="请输入企业简称"></el-input>
                </el-form-item>
              </el-col>
              <!-- 3.3城市 -->
              <el-col :span="6">
                <el-form-item label="城市">
                  <el-row>
                    <el-col :span="11">
                      <!-- 省 -->
                      <el-select v-model="form.provinceVal" placeholder="请选择"
                        @change="handleProvince">
                        <el-option
                          v-for="province in form.provinces"
                          :key="province"
                          :label="province"
                          :value="province"></el-option>
                      </el-select>
                    </el-col>
                    <!-- 市 -->
                    <el-col :span="11" :offset="2">
                      <el-select v-model="form.cityDateVal" placeholder="请选择">
                         <el-option
                          v-for="item in form.cityDate"
                          :key="item"
                          :label="item"
                          :value="item"></el-option>
                      </el-select>
                    </el-col>
                  </el-row>
                </el-form-item>
              </el-col>
              <!-- 3.4按钮区域 -->
              <el-col :span="6">
                <div class="flex-end">
                  <el-button @click="clearForm" :loading="isLoading">清空</el-button>
                  <el-button type="primary" @click="getFilter" :loading="isLoading">搜索</el-button>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-form>

        <!-- 三、提示条 -->
        <el-row class="ques_total">
          <el-alert
            v-if="alertText !== ''"
            :title="alertText"
            type="info"
            :closable="false"
            show-icon>
          </el-alert>
        </el-row>

        <!-- 四、表格区域 -->
        <el-table
          v-loading="isLoading"
          element-loading-text="拼命加载中"
          :data="questions"
          style="width: 100%">
          <!-- 1.试题编号 -->
          <el-table-column
            prop="number"
            label="试题编号"
            width="120">
          </el-table-column>
          <!-- 2.学科 -->
          <el-table-column
            prop="subject"
            label="学科"
            width="120">
          </el-table-column>
          <!-- 3.目录 -->
          <el-table-column
            prop="catalog"
            label="目录"
            width="120">
          </el-table-column>
          <!-- 4.题型 -->
          <el-table-column
            label="题型"
            width="120">
            <template slot-scope="scope">
              <span v-if="scope.row.questionType === '1'">单选</span>
              <span v-else-if="scope.row.questionType === '2'">多选</span>
              <span v-else-if="scope.row.questionType === '3'">简答</span>
            </template>
          </el-table-column>
          <!-- 5.题干 -->
          <el-table-column
            label="题干">
            <template slot-scope="scope">
              <div>{{ scope.row.question | html2Text }}</div>
            </template>
          </el-table-column>
          <!-- 6.录入时间 -->
          <el-table-column
            label="录入时间"
            width="180">
            <template slot-scope="scope">
              <span>{{ scope.row.addDate | parseTimeByString('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <!-- 7.难度 -->
          <el-table-column
            prop="difficulty"
            label="难度"
            width="100">
              <template slot-scope="scope">
              <span v-if="scope.row.difficulty === '1'">简单</span>
              <span v-else-if="scope.row.difficulty === '2'">一般</span>
              <span v-else-if="scope.row.difficulty === '3'">困难</span>
            </template>
          </el-table-column>
          <!-- 8.录入人 -->
          <el-table-column
            prop="creator"
            label="录入人"
            width="120">
          </el-table-column>
          <!-- 9.操作 -->
          <el-table-column
            label="操作"
            width="200">
            <template slot-scope="scope">
              <!-- 预览 -->
              <el-button type="primary" icon="el-icon-view" plain circle @click="preQuestion(scope.row.id)"></el-button>
              <!-- 修改 -->
              <el-button type="success" icon="el-icon-edit" plain circle @click="editQuestion(scope.row.id)"></el-button>
              <!-- 删除 -->
              <el-button type="danger" icon="el-icon-delete" plain circle @click="delQuestion(scope.row.id)"></el-button>
              <!-- 加精选 -->
              <el-button type="warning" icon="el-icon-check" plain circle @click="addChoice(scope.row.id)"></el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 五、分页区域 -->
        <div class="ques_pagination">
          <el-pagination
            :disabled="isLoading"
            background
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            :current-page="page"
            :page-sizes="[5, 10, 20, 50]"
            :page-size="pagesize"
            layout="prev, pager, next, sizes, jumper"
            :total="counts">
          </el-pagination>
        </div>
      </el-card>

      <!-- 六、预览区域 -->
      <questions-preview v-model="previewData"></questions-preview>
    </div>
  </div>
</template>

<script>
// 引入接口
// 基础题库
import { list, choiceAdd, remove } from '@/api/hmmm/questions'
// 学科
import { simple } from '@/api/hmmm/subjects'
// 目录
import { simple as direSimple } from '@/api/hmmm/directorys'
// 标签
import { simple as tagSimple } from '@/api/hmmm/tags'
// 三个常量：题型、难度、方向
import { questionType, difficulty, direction } from '@/api/hmmm/constants'
// 用户
import { simple as userSimple } from '@/api/base/users'
// 城市
import { provinces, citys } from '@/api/hmmm/citys.js'
// 引入预览对话框组件
import QuestionsPreview from '../components/questions-preview'
export default {
  name: 'questions-list',
  data () {
    return {
      form: { // 筛选-表单区域
        subjects: [], // 学科
        subjectValue: null, // 学科值
        directorys: [], // 二级目录
        directoryValue: null, // 二级目录值
        tags: [], // 标签
        tagValue: null, // 标签值
        keyword: null, // 关键字
        questionTypes: questionType, // 题型
        questionTypeVal: null,
        difficultys: difficulty, // 难度
        difficultyVal: null,
        directions: direction, // 方向
        directionVal: null,
        users: [], // 录入人
        userVal: null, // 录入人值
        remarks: null, // 题目备注
        shortName: null, // 企业简称
        provinces: [], // 省
        provinceVal: null,
        cityDate: [], // 市
        cityDateVal: null
      },
      questions: [], // 表格-基础题库列表
      previewData: { // 预览-区域
        dialogFormVisible: false, // 对话框-详情预览
        questionId: null // 问题id
      },
      options: [], // 预览-题目选项
      counts: null, // 分页-数据总数
      page: 1, // 分页-当前页码
      pages: null, // 分页-总页数
      pagesize: 5, // 分页-每页数据量
      alertText: '', // 提示条
      isLoading: true // 加载中效果
    }
  },
  created () {
    // 渲染题库列表
    this.loadQuestions()
    // 渲染筛选-学科
    this.loadSubject()
    // 渲染筛选-录入人
    this.loadUsers(this.keyword)
    // 渲染筛选-省
    this.getCityData()
  },
  components: {
    // 注册预览对话框组件
    QuestionsPreview
  },
  methods: {
    // 1.点击‘新增试题’跳转到‘试题录入’（questions-new）页
    toQuestionNew () {
      this.$router.push('new')
    },
    // 2.渲染基础题库列表
    async loadQuestions () {
      this.isLoading = true
      // 请求参数
      var params = {
        page: this.page,
        pagesize: this.pagesize,
        subjectID: this.form.subjectValue, // 学科值
        catalogID: this.form.directoryValue, // 二级目录值
        tags: this.form.tagValue, // 标签值
        keyword: this.form.keyword, // 关键字
        questionType: this.form.questionTypeVal, // 试题类型
        difficulty: this.form.difficultyVal,
        direction: this.form.directionVal, // 方向
        creatorID: this.form.userVal, // 录入人值
        remarks: this.form.remarks, // 题目备注
        shortName: this.form.shortName, // 企业简称
        province: this.form.provinceVal, // 省
        city: this.form.cityDateVal // 市
      }
      try {
        const { data: res } = await list(params) // 这里封装了请求方式
        this.counts = res.counts // 数据总数
        this.questions = res.items // 基础题库列表
        this.pages = res.pages // 总页数
        this.alertText = `数据一共 ${this.counts} 条`
        // console.log(res)
        this.isLoading = false
      } catch {
        this.$message.error('请求出错，请检查接口！')
        this.isLoading = false
      }
    },
    // 3.改变当前页
    handleCurrentChange (page) {
      this.page = page
      this.loadQuestions()
    },
    // 4.改变当前页显示数量
    handleSizeChange (pagesize) {
      // console.log(pagesize)
      this.pagesize = pagesize
      this.loadQuestions()
    },
    // 5.预览出现弹出框
    async preQuestion (questionId) {
      // 打开对话框
      this.previewData.dialogFormVisible = true
      this.previewData.questionId = questionId
    },
    // 6.修改
    editQuestion (idStr) {
      // console.log(idStr)
      this.$router.push({
        name: 'questions-new',
        params: {
          id: idStr
        }
      })
    },
    // 7.加入精选
    addChoice (quesID) {
      try {
        this.$confirm('此操作将该题目加入精选，是否继续？', '提示', { type: 'info' })
          .then(async () => {
            // 参数
            var data = {
              id: quesID,
              choiceState: 1
            }
            await choiceAdd(data)
            this.$message.success('加入精选题库成功！')
            // 跳转到精选题库
            this.$router.push('choice')
          })
          .catch(() => {
            this.$message.info('已取消操作！')
          })
      } catch {
        this.$message.error('加入精选失败，请检查接口！')
      }
    },
    // 8.删除
    async delQuestion (quesID) {
      try {
        this.$confirm('此操作将永久删除该题目，是否继续？', '提示', { type: 'warning' })
          .then(async () => {
            await remove({ id: quesID })
            this.$message.success('删除成功！')
            this.loadQuestions()
          })
          .catch(() => {
            this.$message.info('已取消删除！')
          })
      } catch {
        this.$message.error('删除失败，请检查接口！')
      }
    },
    // 其他功能封装到了预览组件
    // 10.渲染学科列表
    async loadSubject () {
      var params = {
        page: null,
        pagesize: 100
      }
      try {
        // 简单学科列表
        const { data: res } = await simple(params)
        this.form.subjects = res
      } catch {
        this.$message.error('请求失败，请检查接口！')
      }
    },
    // 11.学科列表变化
    async subjectChange (subID) {
      // 先清空子级下拉框里面的内容
      this.form.directoryValue = ''
      this.form.tagValue = ''
      try {
        // 简单目录列表
        const { data: res } = await direSimple({ subjectID: subID })
        // console.log(res)
        // 赋值给二级目录
        this.form.directorys = res
        this.form.directoryValue = res[0] ? res[0].value : null
      } catch (err) {
        console.log(err) // for debug
        this.$message.error('请求失败，请检查接口！')
      }
      try {
        // 标签
        const { data: tagRes } = await tagSimple({ subjectID: subID })
        this.form.tags = tagRes
        // 标签二级联动
        this.form.tagValue = tagRes[0] ? tagRes[0].value : null
      } catch {
        this.$message.error('请求失败，请检查接口！')
      }
    },
    // 12.获取用户列表
    async loadUsers (keyword) {
      var params = {
        keyword: keyword
      }
      try {
        const { data: userRes } = await userSimple(params)
        this.form.users = userRes
      } catch {
        this.$message.error('请求失败，请检查接口！')
      }
    },
    // 13.获取省
    getCityData () {
      this.form.provinces = provinces()
    },
    // 14.选省获取到市（获取省后触发的回调）
    handleProvince (e) {
      this.form.cityDate = citys(e)
      // 默认选第一个值
      this.form.cityDateVal = this.form.cityDate[0]
    },
    // 15、清空功能
    clearForm () {
      this.form.subjectValue = null // 学科值
      this.form.directoryValue = null // 二级目录值
      this.form.directorys = [] // 二级目录
      this.form.tags = [] // 标签
      this.form.tagValue = null // 标签值
      this.form.keyword = null // 关键字
      this.form.userVal = null // 录入人值
      this.form.remarks = null // 题目备注
      this.form.shortName = null // 企业简称
      this.form.provinceVal = null // 省
      this.form.cityDateVal = null // 市
      this.form.cityDate = [] // 市
      this.form.questionTypes = questionType // 题型
      this.form.difficultys = difficulty // 难度
      this.form.directions = direction // 方向
      this.form.questionTypeVal = null
      this.form.difficultyVal = null
      this.form.directionVal = null
      // 清空之后重新渲染
      this.loadQuestions()
    },
    // 16、筛选搜索
    getFilter () {
      this.loadQuestions()
    }
  }
}
</script>

<style scoped>
  .filter-container {
    padding: 0;
  }
  /* 下拉列表 */
  .ques_form /deep/ .el-select {
    display: block;
  }
  /* 新增试题 */
  .addQuestion {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 20px;
  }
  .flex-end {
    display: flex;
    justify-content: flex-end;
  }
  /* 提示条 */
  .ques_total {
    margin-bottom: 20px;
  }
  /* 分页 */
  .ques_pagination {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }
  /* 预览 */
  .row_preview {
    margin-bottom: 10px;
  }
  /* 题干 */
  .question {
    color: #0f0fff;
  }
</style>
